package org.cheniy.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.cheniy.domain.strategy.model.entity.StrategyRuleEntity;
import org.cheniy.domain.strategy.repository.IStrategyRepository;
import org.cheniy.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.cheniy.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.cheniy.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author cheniy
 * @description 黑名单过滤责任链节点
 * @create 2025/3/7 22:24
 */

@Slf4j
@Component("rule_blacklist")
public class BackListLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository iStrategyRepository;

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {

        log.info("抽奖责任链-黑名单开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());


        // 1. 获取规则实体
        StrategyRuleEntity strategyRuleEntity = iStrategyRepository.queryStrategyRule(strategyId, ruleModel());

        // 2. 获取黑名单的保底奖品id，黑名单用户列表
        String ruleValue = strategyRuleEntity.getRuleValue();
        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        Integer awardId = Integer.parseInt(splitRuleValue[0]);
        String[] blackListUsers = splitRuleValue[1].split(Constants.SPLIT);
        // 3. 判断当前用户是否为黑名单，是则返回保底id，不是则给到下一责任链节点
        for (String blackListUser:blackListUsers){
            if (blackListUser.equals(userId)){
                log.info("抽奖责任链-黑名单接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
                return DefaultChainFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .logicModel(ruleModel())
                        // 写入默认配置黑名单奖品值 0.01 ~ 1 积分，也可以配置到数据库表中
                        .awardRuleValue("0.01,1")

                        .build();
            }

        }
        return this.next().logic(userId, strategyId);
    }

    @Override
    public String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }

}
